package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.streams.processor.TaskId;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2022/11/14 10:28
 * @Version 1.0
 */
@Service
@Slf4j
public class TaskServiceImpl implements TaskService{

    @Resource
    private TaskinfoMapper taskinfoMapper;

    @Resource
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult addTask(Task task) {

        //存表
        saveTask(task);

        //获取5分钟之后时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        long afterTime = calendar.getTimeInMillis();

        //如果执行时间小于当前时间,写入数据到list
        if(task.getExecuteTime() <= System.currentTimeMillis()){
            String key = ScheduleConstants.TOPIC +task.getTaskType() + "-" + task.getPriority();
            cacheService.lLeftPush(key, JSON.toJSONString(task));
        }else if(task.getExecuteTime() <= afterTime){
            String key = ScheduleConstants.FUTURE +task.getTaskType() + "-" + task.getPriority();
            cacheService.zAdd(key,JSON.toJSONString(task),task.getExecuteTime());
        }
        return ResponseResult.okResult(task.getTaskId());
    }

    /**
     * 分别存入info及infoLog表
     */
    public void saveTask(Task task){
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task,taskinfo);
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
        taskinfoMapper.insert(taskinfo);

        TaskinfoLogs logs = new TaskinfoLogs();
        BeanUtils.copyProperties(taskinfo,logs);
        logs.setVersion(1);
        logs.setStatus(ScheduleConstants.SCHEDULED);
        taskinfoLogsMapper.insert(logs);
    }


    @Override
    public Task poll(Integer type,Integer prority){
        String key = ScheduleConstants.TOPIC +type + "-" + prority;
        String jsonString = cacheService.lRightPop(key);
        if(StringUtils.isEmpty(jsonString)){
            return null;
        }
        Task task = JSON.parseObject(jsonString, Task.class);

        updateDb(task);

        return task;
    }

    /**
     *
     * 更新数据库
     * @param task
     */
    private void updateDb(Task task){
        taskinfoMapper.deleteById(task.getTaskId());

        TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(task.getTaskId());
        taskinfoLogs.setStatus(ScheduleConstants.EXECUTED);
        taskinfoLogsMapper.updateById(taskinfoLogs);
    }


    @Scheduled(cron = "0 0/1 * * * ?")
    public void pushExecTask(){
        log.info("开始执行zset到list任务");
        String flag = cacheService.tryLock("Task-pushExecTask",30000);
        if(flag == null){
            log.info("未获取到锁，不执行");
            return;
        }
        Set<String> fetures = cacheService.scan(ScheduleConstants.FUTURE + "*");
        if(CollectionUtils.isEmpty(fetures)){
            log.info("没有需求执行的任务");
            return;
        }
        for(String fetureKey : fetures){
            String listKey = ScheduleConstants.TOPIC + fetureKey.split(ScheduleConstants.FUTURE)[1];
            Set<String> taskList = cacheService.zRangeByScore(fetureKey, 0, System.currentTimeMillis());
            cacheService.refreshWithPipeline(fetureKey,listKey,taskList);
            log.info("完成key:{}的数据刷新",fetureKey);
        }
    }

    @Scheduled(cron = "0 0/5 * * * ?")
    public void loadDataToZset(){
        log.info("开始执行从数据库将最近5分钟需要执行的任务添加到zset中");
        String flag = cacheService.tryLock("Task-loadDataToZset",3000);
        if(flag == null){
            log.info("未获取到锁，不执行");
            return;
        }
        //查询5内的数据
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);

        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));
        for(Taskinfo taskinfo : taskinfos) {
            String key = ScheduleConstants.FUTURE + taskinfo.getTaskType() + "-" + taskinfo.getPriority();
            Task task = new Task();
            BeanUtils.copyProperties(taskinfo,task);
            task.setExecuteTime(taskinfo.getExecuteTime().getTime());
            cacheService.zAdd(key,JSON.toJSONString(task),taskinfo.getExecuteTime().getTime());
        }
    }

}